package com.amqr.movetest.widget;

import android.content.Context;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

/**
 * User: LJM
 * Date&Time: 2017-04-23 & 15:57
 * Describe: Describe Text
 */
public class FoldView extends ViewGroup {


    private MyRecyclerLayout mUpView;
    private ViewGroup mDownView;
    private ViewDragHelper viewDragHelper;
    private int mUpWidth;
    private int mUpHeight;
    private int mDownWidth;
    private int mDownHeight;
    private boolean foldState = false;


    public FoldView(Context context) {
        super(context);
    }

    public FoldView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FoldView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private  OnSwitchListener mOnSwitchListener;

    public interface OnSwitchListener{
        void baseOpenState();
    }

    public void setSwitchListener(OnSwitchListener switchListener){
        this.mOnSwitchListener = switchListener;
    }


    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mUpView = (MyRecyclerLayout) getChildAt(0);
        mDownView = (ViewGroup) getChildAt(1);
        viewDragHelper = ViewDragHelper.create(this,new MyDrawHelper());

        if(mOnSwitchListener!=null){
            mOnSwitchListener.baseOpenState();
        }

        foldState = false;
        isOpen(foldState);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 测量顶部
        LayoutParams upLayoutParams = mUpView.getLayoutParams();
        int upHeight = MeasureSpec.makeMeasureSpec(upLayoutParams.height,MeasureSpec.EXACTLY);
        mUpView.measure(widthMeasureSpec,upHeight);

        // 测量底部
        LayoutParams downLayoutParams = mDownView.getLayoutParams();
        int downHeight = MeasureSpec.makeMeasureSpec(downLayoutParams.height,MeasureSpec.EXACTLY);
        mDownView.measure(widthMeasureSpec,downHeight);
    }

    @Override
    protected void onLayout(boolean b,  int left, int top, int right, int bottom) {
        mUpWidth = mUpView.getMeasuredWidth();
        mUpHeight = mUpView.getMeasuredHeight();
        mUpView.layout(0,0, mUpWidth, mUpHeight);

        mDownWidth = mDownView.getMeasuredWidth();
        mDownHeight = mDownView.getMeasuredHeight();
        mDownView.layout(0, 0, mDownWidth,  mDownHeight);
    }

    class MyDrawHelper extends ViewDragHelper.Callback {
        /**
         * Touch的down事件会回调这个方法 tryCaptureView
         *
         * @Child：指定要动的孩子  （哪个孩子需要动起来）
         * @pointerId: 点的标记
         * @return : ViewDragHelper是否继续分析处理 child的相关touch事件
         */
        @Override
        public boolean tryCaptureView(View child, int pointerId) {

            return mDownView == child ;
        }
        // Touch的move事件会回调这面这几个方法
        // clampViewPositionHorizontal
        // clampViewPositionVertical
        // onViewPositionChanged
        /**
         *
         * 捕获了水平方向移动的位移数据
         * @param child 移动的孩子View
         * @param left 父容器的左上角到孩子View的距离
         * @param dx 增量值，其实就是移动的孩子View的左上角距离控件（父亲）的距离，包含正负
         * @return 如何动
         *
         * 调用完此方法，在android2.3以上就会动起来了，2.3以及以下是海动不了的
         * 2.3不兼容怎么办？没事，我们复写onViewPositionChanged就是为了解决这个问题的
         */
        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {
            return super.clampViewPositionHorizontal(child,left,dx);
        }
        @Override
        public int clampViewPositionVertical(View child, int top, int dy) {
            //return super.clampViewPositionVertical(child, top, dy);
            return top;
        }
        /**
         * 当View的位置改变时的回调
         * @param changedView  哪个View的位置改变了
         * @param left  changedView的left
         * @param top  changedView的top
         * @param dx x方向的上的增量值
         * @param dy y方向上的增量值
         */
        @Override
        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
            invalidate();
            super.onViewPositionChanged(changedView, left, top, dx, dy);
        }
        /**
         * 相当于Touch的up的事件会回调onViewReleased这个方法
         *
         * @param releasedChild
         * @param xvel x方向的速率
         * @param yvel y方向的速率
         */
        @Override
        public void onViewReleased(View releasedChild, float xvel, float yvel) {
            int mDownTopMove = mDownView.getTop();
            if(mDownTopMove>(mUpHeight/2)){
                //mDownView.layout(0, mUpHeight, mDownWidth, mUpHeight + mDownHeight);
                //viewDragHelper.smoothSlideViewTo(mDownView,0,mUpHeight);

                foldState = true;
                isOpen(foldState);
            }else{
                //mDownView.layout(0,0,mDownWidth,mDownHeight);
                //viewDragHelper.smoothSlideViewTo(mDownView,0,0);
                foldState  = false;

                isOpen(foldState);
            }
            //invalidate();
            super.onViewReleased(releasedChild, xvel, yvel);
            if(mOpenStateListener!=null){
                mOpenStateListener.releaseState();
            }

        }
    }

    public boolean getFoldState(){
        return foldState;
    }



    public interface OpenStateListener{
        void changeState(boolean state);
        void releaseState();
    }

    private OpenStateListener mOpenStateListener;

    public void setOpenStateLisner(OpenStateListener openStateListener){
        this.mOpenStateListener = openStateListener;
    }



    public void isOpen(boolean isOpen){

        if(isOpen){
            //mDownView.layout(0, mUpHeight, mDownWidth, mUpHeight + mDownHeight);
            viewDragHelper.smoothSlideViewTo(mDownView,0,mUpHeight);

            if(mOpenStateListener!=null){
                mOpenStateListener.changeState(true);
            }


            //mUpView.setInterceptState(false);
        }else{
            //mDownView.layout(0,0,mDownWidth,mDownHeight);
            viewDragHelper.smoothSlideViewTo(mDownView,0,0);

            if(mOpenStateListener!=null){
                mOpenStateListener.changeState(false);
            }

            //mUpView.setInterceptState(true);

        }
        invalidate();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //return super.onTouchEvent(event);
        /**Process a touch event received by the parent view. This method will dispatch callback events
         as needed before returning. The parent view's onTouchEvent implementation should call this. */
        viewDragHelper.processTouchEvent(event); // 使用ViewDragHelper必须复写onTouchEvent并调用这个方法
        return true; //消费这个touch
    }

    @Override
    public void computeScroll() {
        //super.computeScroll();
        // 把捕获的View适当的时间移动，其实也可以理解为 smoothSlideViewTo 的模拟过程还没完成
        if(viewDragHelper.continueSettling(true)){
            invalidate();
        }
        // 其实这个动画过渡的过程大概在怎么走呢？
        // 1、smoothSlideViewTo方法进行模拟数据，模拟后就就调用invalidate();
        // 2、invalidate()最终调用computeScroll，computeScroll做一次细微动画，
        //    computeScroll判断模拟数据是否彻底完成，还没完成会再次调用invalidate
        // 3、递归调用，知道数据noni完成。
    }

}
